package eip.chapter5.sequence.impl;

import java.util.List;

import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.log4j.Logger;

import eip.chapter5.sequence.Bill;
import eip.chapter5.sequence.CheckoutBillClient;
import eip.chapter5.sequence.util.JiBXHelper;

public class CheckoutBillClientImpl implements CheckoutBillClient {

	private static final Logger logger = Logger.getLogger(CheckoutBillClientImpl.class);
	
	public void sendBills(List<Bill> billList) {
		try {
			ActiveMQConnection connection = ActiveMQConnection.makeConnection("tcp://localhost:61616");
		    connection.start();
		    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		    Destination destination = session.createQueue("checkoutbill");
			int counter = 1;
			for(Bill bill : billList) {
				TextMessage billMessage = session.createTextMessage();
				billMessage.setStringProperty("JMSXGroupID", "BillsFor" + bill.getGuestName());
				billMessage.setIntProperty("JMSXGroupSeq", 2);
				if(counter == billList.size()) {
					bill.setLastBill(new Boolean(true));
					billMessage.setIntProperty("JMSXGroupSeq", 0);
				}
				String strBill = JiBXHelper.createBillinXML(bill);
				logger.info("sending billMessage " + billMessage);
				billMessage.setText(strBill);
				MessageProducer producer = session.createProducer(destination);
				producer.send(billMessage);
				counter++;
			}
	        
		} catch (Exception e) {
			logger.error("Error while sending bills", e);
		} 
	}
}
